<template>
    <div class="biggest-box">

        <!--        编写页面-->
        <div class="make-moment-page" v-if="flag">
            <!--        logo-->
            <div class="login-heading">
                <div class="logo">
                    <span class="logo-span"><a href="/">芬 享</a></span>
                    <span class="login-text">众享你的喜悦!</span>
                </div>
            </div>
            <div class="make-moment-page-main">
                <el-row :gutter="20">
                    <!--            富文本编辑-->
                    <el-col :span="14">
                        <RickText ref="rickText" :text.sync="text" :changeHtml.sync="form.content"/>
                    </el-col>
                    <el-col :span="10">
                        <!--                其他信息-->
                        <div class="moment-form">

                            <h2 class="moment-form-h2">
                                <font-awesome-icon class="icon" :icon="['fas', 'info-circle']"/>
                                基本信息
                            </h2>

                            <el-form ref="form" :rules="rules" :model="form" label-width="80px">
                                <!--                    标题-->
                                <el-form-item label="标题" prop="title">
                                    <el-input maxlength="30"
                                              minlength="1"
                                              show-word-limit
                                              v-model="form.title"
                                              placeholder="请填写标题"></el-input>
                                </el-form-item>

                                <!--                    简介-->
                                <el-form-item label="简介" prop="description">
                                    <el-input
                                            type="textarea"
                                            v-model="form.description"
                                            :minlength="0"
                                            :maxlength="255"
                                            show-word-limit
                                            rows="5"
                                            resize="none"
                                            placeholder="不写默认为文章前50字符"></el-input>
                                </el-form-item>

                                <!--                    数据域-->
                                <el-form-item label="可见性" prop="dataScope">
                                    <el-radio-group v-model="form.dataScope">
                                        <el-radio :label="item.dictValue" :key="index"
                                                  v-for="(item,index) in dataScopeOption">
                                            {{item.dictLabel}}
                                        </el-radio>
                                    </el-radio-group>
                                </el-form-item>

                            </el-form>

                            <!--                    标签-->
                            <TagSelect ref="tagSelect" :selectTag.sync="selectTag" :num="10"/>

                            <el-alert
                                    type="warning"
                                    show-icon
                                    :closable="false">
                        <span slot="title">
                            请勿发布违反国家法律法规的内容,详见
                            <a class="warning"
                               target="_blank"
                               href="https://blogdev.blog.csdn.net/article/details/113122012">《芬香内容创作规范》</a>
                        </span>
                            </el-alert>

                            <div class="form-btn">
                                <el-button type="info" @click="draft">存为草稿</el-button>
                                <el-button type="primary" @click="submit" :loading="loading">
                                    <span v-if="!loading">点击发布</span>
                                    <span v-else>发布中...</span>
                                </el-button>
                            </div>

                        </div>
                    </el-col>
                </el-row>
            </div>

        </div>


        <!--        发布成功后，隐藏编写页面，防止用户重复提交-->
        <div class="make-success" v-else>
            <el-card class="box-card">
                <!--                小提示-->
                <h2 class="go-manager-h2">
                    <span>
                        <font-awesome-icon :icon="['fas', 'angle-left']"/> 管理文章
                    </span>
                </h2>


                <!--                文章粗略信息-->
                <div class="article-info">
                    <h3 class="article-title">{{form.title}}</h3>
                    <p class="article-desc">
                        {{form.description}}
                    </p>
                    <div class="tip">
                        —— 分享美食,分享生活,分享美好
                    </div>
                </div>

                <!--                跳转，等其他功能-->
                <div class="success-other-func">

                    <span @click="goNewPage(`/moment/${momentId}`)">
                        <font-awesome-icon style="color: #67C23A" :icon="['fas', 'check-circle']"/>
                        发布成功并查看文章
                         <font-awesome-icon :icon="['fas', 'angle-right']"/>
                    </span>

                    <span @click="goNewPage(`/make/moment?momentId=${momentId}`)">重新编辑</span>

                    <span>复制链接</span>

                    <span @click="goNewPage('/make/moment')">再写一篇</span>

                </div>

            </el-card>
        </div>
    </div>

</template>

<script>
    import TagSelect from "@/components/TagSelect"
    import RickText from '@/components/RichText'

    import {getDictData} from '@/api/common/common'
    import {insertOrUpdateMoment, getMomentUpdateById} from "@/api/business/moment"

    import {getItem} from "@/utils/storage"
    import {ajax} from "@/utils/foodcircle"


    export default {
        name: 'MakeMoment',
        data() {
            return {
                isUpdate: false,
                interval: null,//用于自动保存
                flag: true,
                loading: false,
                momentId: -1,//如果不为-1，说明是修改文章
                dataScopeOption: [],
                text: "",
                form: {
                    momentId: -1,
                    title: "",
                    content: "",
                    description: "",
                    dataScope: "3",
                    status: 0, //表示临时状态
                    tags: []
                },
                selectTag: [],
                rules: {
                    title: [
                        {required: true, message: '请设置标题', trigger: 'blur'},
                        {min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur'}
                    ],
                    dataScope: [
                        {required: true, message: '请选择可见性', trigger: 'change'}
                    ],
                }
            };
        },
        methods: {
            /**
             * 获取描述，
             * 如果有填写，则使用填写得
             * 如果没有，截取内容得前120字符(有图片怎么办？)
             */
            getDesc() {
                if (this.form.description.trim() === '') {
                    /**
                     * 如果超过，就截取120字符
                     */
                    if (this.text.trim().length >= 120) {
                        return this.text.trim().substring(0, 121)
                    } else {
                        /**
                         * 如果没超过，就获取所有
                         */
                        return this.text.trim()
                    }
                }
                return this.form.description.trim()
            },
            /**
             * 初始数据
             */
            async initData() {
                let res = await this.insertOrUpdateMoment()
                this.setData(res.data)
            },
            /**
             * 设置数据
             */
            setData(moment) {
                this.form.momentId = moment.momentId
                /**
                 * 如果momentId不为-1，说明是修改状态，这需要更新以下数据
                 */
                if (this.momentId && this.momentId !== -1) {
                    this.form.title = moment.title
                    this.form.content = moment.content
                    this.form.description = moment.description
                    this.form.dataScope = moment.dataScope + ""
                    this.form.status = moment.status
                    this.$refs.rickText.updateHtml(moment.content)
                    this.$refs.tagSelect.updateTag(moment.tags)
                }
            },
            /**
             * 发起请求
             */
            async insertOrUpdateMoment() {
                let params = {
                    momentId: this.form.momentId,
                    title: this.form.title.trim(),
                    content: this.form.content.trim(),
                    description: this.getDesc().trim(),
                    dataScope: parseInt(this.form.dataScope),
                    status: this.form.status,
                    tags: this.selectTag,
                }
                this.form.description = params.description
                /**
                 * 地点:是不可以修改的,只有第一次，也就是momentId==-1的时才可以设置地点
                 */
                if (!this.momentId || this.momentId === -1) {
                    let addr = getItem(this.$Constants.CURRENT_CITY);
                    addr = addr ? addr : {regionId: 0}
                    params.addr = addr.regionId
                }

                let res = await insertOrUpdateMoment(params)
                return res
            },
            /**
             * 发布文章
             */
            submit() {
                this.$refs.form.validate(async (valid) => {
                    if (valid) {
                        //将状态改为已发布状态
                        this.form.status = this.$Constants.PUBLISH_STATUS
                        let res = await this.insertOrUpdateMoment()
                        if (res.code !== 200) {
                            this.msgError(this.$Constants.ERROR_MSG)
                            return
                        } else {
                            this.msgSuccess("发布成功!请耐心等待审核通过")
                        }
                        /**
                         * 防止重复点击
                         * 发表成功后，做一些收尾工作
                         */
                        this.momentId = this.form.momentId
                        this.form.momentId = undefined
                        this.flag = false
                        window.onbeforeunload = null
                        clearInterval(this.interval)
                    } else {
                        this.msgWarn("请填写基本信息")
                        return false;
                    }
                })
            },
            /**
             * 存为草稿
             */
            async draft() {
                this.form.status = this.$Constants.DRAFT_STATUS
                let res = await this.insertOrUpdateMoment()
                if (res.code !== 200) {
                    this.msgError(this.$Constants.ERROR_MSG)
                } else {
                    this.msgSuccess("保存成功!")
                }
            },
            /**
             * 删除文章，同步
             */
            deleteMomentById() {
                ajax({
                    url: this.$Constants.BASE_URL + `/moment/${this.form.momentId}`,
                    type: 'post',
                    data: {},
                    dataType: 'json',
                    timeout: 10000,
                    contentType: "application/json",
                    success: function (data) {
                        console.log(data);
                    },
                    //异常处理
                    error: function (e) {
                        console.log(e);
                    }
                })
            },
            /**
             * 获取文章信息
             */
            getMoment(id) {
                getMomentUpdateById(id).then(res => {
                    this.setData(res.data)

                }).catch(() => {

                })
            },
            /**
             * TODO 自动保存
             */
            autoSave() {
                this.insertOrUpdateMoment()
            },
            /**
             * 绑定窗口刷新等事件
             */
            boundWindow() {
                let _this = this
                /**
                 * 打开该页面后，在该页面没有任何操作，不会有提示，在input中输入文字或者其他信息，
                 * 刷新/返回/关闭该页面都会有提示；刷新/返回/关闭操作时间间隔太短有时有提示，有时没有。
                 * 所以只有在该页面有操作，并且时间间隔大于5秒左右即会有提示。
                 */
                window.onbeforeunload = function (e) {
                    e = e || window.event;
                    // 兼容IE8和Firefox 4之前的版本
                    if (e) {
                        e.returnValue = "离开时提示用户是否要保存,防止误操作";
                    }
                    // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
                    return '离开时提示用户是否要保存,防止误操作';
                }

                window.onunload = async function () {
                    /**
                     * 如果当前处于临时状态,在关闭之前,去数据库将数据删除
                     */
                    if (_this.form.status === _this.$Constants.TEMP_STATUS) {
                        _this.deleteMomentById()
                    }

                }
            },
            /**
             * 初始化
             */
            init() {
                getDictData({
                    dictType: "data_scope"
                }).then(res => {
                    this.dataScopeOption = res.data
                })

                /**
                 * 如果有值，说明是编辑,需要获取文章数据
                 */
                this.momentId = this.$route.query.momentId
                if (this.momentId) {
                    this.getMoment(this.momentId)
                } else {
                    this.initData()
                }
            }
        },
        mounted() {
            //绑定相关事件
            this.boundWindow()

            //初始化
            this.init()

            let that = this
            /**
             * 设置定时，定时保存文章
             * 页面关闭的时候取消定时器,发表成功的时候取消定时器
             */
            this.interval = setInterval(function () {
                that.autoSave()
            }, this.$Constants.AUTO_SAVE_MIN * 60 * 1000)//一分钟为单位
        },
        destroyed() {
            window.onbeforeunload = null
            window.onunload = null
            clearInterval(this.interval)
        },
        components: {
            RickText,
            TagSelect
        }
    }
</script>

<style scoped lang='less'>
    .biggest-box {

        .make-moment-page {

            background-color: #eff3f5;

            .login-heading {
                height: 10vh;
                line-height: 10vh;
                padding: 0 5vw;
                background-color: white;
                margin-bottom: 20px;

                .logo {
                    .logo-span {
                        padding: 15px 8px;
                        background-color: rgb(255, 195, 0);
                        border-radius: 15px;
                        font-size: 14px;
                        font-weight: 600;
                        cursor: pointer;
                        margin-right: 10px;
                    }

                    .login-text {
                        color: #E6A23C;
                    }
                }
            }

            .make-moment-page-main {
                padding: 0 5vw;

                .moment-form {
                    .moment-form-h2 {
                        font-weight: 700;
                        font-size: 20px;
                        margin: 20px 0;
                        color: #909399;
                    }

                    .warning {
                        color: rgb(51, 153, 234);
                    }

                    .form-btn {
                        margin-top: 20px;
                        text-align: right;
                    }
                }
            }
        }


        .make-success {
            display: flex;
            width: 100vw;
            height: 100vh;
            align-items: center;
            justify-content: center;
            background-color: rgb(244, 244, 244);


            > .box-card {
                width: 550px;
                min-height: 300px;

                .go-manager-h2 {
                    height: 30px;
                    line-height: 30px;
                    margin-bottom: 30px;
                    color: #409EFF;
                    font-size: 14px;

                    > span {
                        cursor: pointer;
                    }
                }

                .article-info {
                    padding: 10px;
                    background-color: #F2F6FC;
                    margin-bottom: 20px;

                    .article-title {
                        font-size: 20px;
                        height: 30px;
                        line-height: 30px;
                        color: #606266;
                    }

                    .article-desc {
                        margin-top: 10px;
                        font-size: 14px;
                        line-height: 20px;
                        word-wrap: break-word;
                        color: #909399;
                        display: -webkit-box;
                        -webkit-box-orient: vertical;
                        -webkit-line-clamp: 3;
                        overflow: hidden;
                    }

                    .tip {
                        text-align: right;
                        height: 30px;
                        line-height: 30px;
                        font-size: 14px;
                        color: #909399;
                        margin-top: 15px;
                    }
                }

                .success-other-func {
                    display: flex;
                    align-items: center;
                    height: 100px;
                    justify-content: space-between;

                    > span {
                        font-size: 14px;
                        cursor: pointer;
                        color: #409EFF;
                    }
                }


            }

        }

    }


</style>